/********************************************************************
 * PROJECT: CSAIR ROST PROJECT.
 * SUPPLIER: FOREVER OPEN SOURCE SOFTWARE INC.
 ********************************************************************
 * FILE: CheckableList.java
 * (C) Copyright Foliage Team 2013, All Rights Reserved.
 ********************************************************************/
package org.foliage.rcp.ui.custom;

import java.util.HashSet;
import java.util.Set;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class CheckableList extends Table {

	// ----------------------------------------------- 

	private boolean isSelectVisible;

	// ----------------------------------------------- 

	public CheckableList(Composite parent, int style) {
		super(parent, checkStyle(style));
		init();
		initListeners();
	}

	// ----------------------------------------------- 

	@Override
	protected void checkSubclass() {}

	// ----------------------------------------------- 

	static int checkStyle(int style) {
		int mask = SWT.V_SCROLL | SWT.BORDER;
		style &= mask;
		style |= SWT.CHECK;
		return style;
	}

	// ----------------------------------------------- 

	void init() {
		setLayout(new FillLayout());
		setHeaderVisible(false);
		setLinesVisible(true);
		setSelectVisible(true);
		TableColumn column = new TableColumn(this, SWT.NONE);
		column.setWidth(120);
	}

	void initListeners() {
		addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent event) {
				if (event.detail == SWT.CHECK) {
					TableItem item = (TableItem) event.item;
					if (isSelectVisible && indexOf(item) == 0) {
						for (TableItem elementItem : getItems()) {
							elementItem.setChecked(item.getChecked());
						}
					}
				}
			}

		});
	}

	// ----------------------------------------------- 

	public void add(String text, boolean isChecked) {
		TableItem item = new TableItem(this, SWT.NONE);
		item.setChecked(isChecked);
		item.setText(text);
	}

	public void setSelectVisible(boolean isVisible) {
		isSelectVisible = isVisible;
		if (isVisible) {
			TableItem item = new TableItem(this, SWT.NONE, 0);
			item.setChecked(false);
			item.setText("全选");
		}
	}

	public String[] getCheckedTexts() {
		Set set = new HashSet();
		for (TableItem item : getItems()) {
			if (item.getChecked()) {
				if ((isSelectVisible && indexOf(item) != 0) || !isSelectVisible) {
					set.add(item.getText());
				}
			}
		}
		return (String[]) set.toArray(new String[set.size()]);
	}
}
